package com.frx.leetcode.one;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author: xrf96
 * @Description: 返回没有重复字符的最长子串
 * "abcabcbb"  -> "abc"
 * @Date: 2020/1/7 18:13
 * @Version: 1.0
 */
public class LongestSubStr {

    public static void main(String[] args){
        String s = "abcabcbb";
        System.out.println(solution2(s));
        System.out.println(solution3(s));

    }
    public static int solution1(String s) {
        int n = s.length();
        int ans = 0;
        for (int i=0;i<n;i++){
            for (int j=i+1;j<=n;j++){
                if (allUnique(s,i,j)){
                    ans = Math.max(ans,j-i);
                }
            }
        }
        return ans;
    }
    public static boolean allUnique(String s,int start,int end){
        Set<Character> set = new HashSet<>();
        for (int i=start;i<end;i++){
            Character ch = s.charAt(i);
            if (set.contains(ch)){
                return false;
            } else {
                set.add(ch);
            }
        }
        return true;
    }

    public static int solution2(String s){
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int i = 0;
        int j = 0;
        int ans = 0;
        while (i < n && j < n){
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans,j-i);
            } else {
                set.remove(i++);
            }
        }


        return ans;
    }

    /**
     * @description 解法3 实现跳跃
     * @param s
     * @return
     */
    public static int solution3(String s){
        int n = s.length();
        int ans = 0;
        Map<Character,Integer> map = new HashMap<>();
        for (int j=0,i=0;j<n;j++){
            if (map.containsKey(s.charAt(j))){
                i = Math.max(map.get(s.charAt(j)),i);
            }
            ans = Math.max(ans,j-i+1);
            map.put(s.charAt(j),j+1);
        }


        return ans;
    }


}
